<template>
  <div>
    <div class="search">
      <input type="text" v-model="keyword" class="search-input" placeholder="搜索城市名">
    </div>

    <div class="search-content" v-show="keyword">
      <ul>
        <li class="search-item" v-for="item of list" :key="item.id" @click="changeCurrentCity(item.name)">
          {{item.name}}
        </li>
        <li class="search-item" v-show="list_length">
          搜索不到
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  name: "CitySearch",
  props: ['cities'],
  data() {
    return {
      keyword: '',
      list: [],
      timer: null
    }
  },
  computed: {
    list_length() {
      return !this.list.length
    }
  },
  watch: {
    keyword() {
      if (this.timer) {
        clearTimeout(this.timer);
      }

      if (!this.keyword) {
        this.list = [];
        return;
      }

      this.timer = setTimeout(() => {
        const result = [];
        for (let i in this.cities) {
          this.cities[i].forEach((value) => {
            if (value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) {
              result.push(value);
            }
          })
        }

        this.list = result;
      }, 100);
    }
  },
  methods: {
    changeCurrentCity(city_name) {
      console.log(city_name);
      this.$store.dispatch('changeCity', city_name);
      this.$router.push('/');
    }
  }
}
</script>

<style>
.search {
  height: .72rem;
  background-color: #00bcd4;

  padding: 0 .2rem;
}

.search .search-input {
  line-height: .62rem;
  width: 100%;
  border-radius: .06rem;
  text-align: center;
}

.search-content {
  z-index: 1;
  overflow: hidden;
  position: absolute;
  top: 1.56rem;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #eeeeee;
}

.search-content .search-item {
  line-height: .62rem;
  padding-left: .2rem;
  background-color: #ffffff;

  border-bottom: 1px solid #cccccc;
}
</style>